import { defineStore } from 'pinia';
import { store } from '@/store';
import {
  ACCESS_TOKEN,
  CURRENT_PHOTO,
  CURRENT_ROLES,
  CURRENT_USER,
  IS_SCREENLOCKED,
  USERNAME,
  PASSWORD,
  IS_AUTOLOGIN,
  CURRENT_PERMISSIONS,
} from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';

import { getUserInfo as getUserInfoApi, getTenantByAccount, verifyLogin } from '@/api/system/user'; // 导入新接口
import { storage } from '@/utils/Storage';
import user from 'mock/user';
import { hashMd5 } from '@/utils/md5Util';

export type UserInfoType = {
  // TODO: add your own data
  username: string;
  email: string;
};

export interface IUserState {
  token: string;
  // 2025-08-25 hej nickname 昵称
  nickname: string;
  avatar: string;
  permissions: any[];
  // 2025-08-25 hej roles 角色
  roles: any[];
  // 冗余信息
  info: UserInfoType;
  username: string;
  welcome: string;
}

const expire = 7 * 24 * 60 * 60;

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    nickname: '',
    avatar: storage.get(CURRENT_PHOTO, null),
    // 权限处理
    // permissions: [],
    permissions: storage.get(CURRENT_PERMISSIONS, []),
    // 2025-08-25 hej roles 角色
    roles: storage.get(CURRENT_ROLES, []),
    info: storage.get(CURRENT_USER, {}),

    username: '',
    welcome: '',
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setNickName(nickname: string) {
      this.nickname = nickname;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setRoles(roles) {
      this.roles = roles;
    },
    // 冗余
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    // 登录
    async login(params: any) {
      // 1. 第一步：根据账户查询租户信息 loginBefore
      // const accountParam ={
      //   account: params.username
      // };
      // console.log(accountParam);
      // 假设用户名即租户查询账户
      const tenantResponse = await this.loginBofore(params);
      // await getTenantByAccount(accountParam);
      const tenantList = tenantResponse;
      if (!tenantList || tenantList.length === 0) {
        throw new Error('未查询到租户信息');
      }
      // 1.2 loginAfter
      const tenant = tenantList[0];
      const response = await this.loginAfter(params, tenant);
      // 取第一个租户信息（如有多租户需求可在此处增加选择逻辑）
      // const { tenantCode, parentTenantCode } = tenant;
      // // 2. 第二步：调用租户登录验证接口
      // // 2.1 TODO 密码需要加密一下再传递;
      // const loginParams = {
      //   userName: params.username,
      //   password: params.password,
      //   tenantCode,
      //   parentTenantCode
      // };
      // const response = await verifyLogin(loginParams);
      const { data, code } = response;
      if (code === ResultEnum.SUCCESS) {
        const token = data.token;
        storage.set(ACCESS_TOKEN, token, expire);
        storage.set(CURRENT_USER, data, expire);
        storage.set(IS_SCREENLOCKED, false);
        this.setUserInfo(data);
        this.setToken(token);
        if (params.autoLogin) {
          storage.set(USERNAME, params.username);
          storage.set(PASSWORD, params.password);
          storage.set(IS_AUTOLOGIN, params.autoLogin);
        } else {
          storage.set(USERNAME, '');
          storage.set(PASSWORD, '');
          storage.set(IS_AUTOLOGIN, false);
        }
        /***
         *    storage.set(PASSWORD, e.password)) : (storage.set(USERNAME, ""),
              storage.set(PASSWORD, "")),
              storage.set(IS_AUTOLOGIN, e.autoLogin);
         */
        this.setToken(token);
        await this.acquireUserInfo(response);
      }

      return response;
    },

    loginBofore(params: any) {
      // 1. 第一步：根据账户查询租户信息 loginBefore
      const accountParam = {
        account: params.username,
      };
      // getTenantByAccount(accountParam)
      return new Promise((resolve, reject) => {
        getTenantByAccount(accountParam)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    loginAfter(params: any, tenant: any) {
      // 取第一个租户信息（如有多租户需求可在此处增加选择逻辑）
      const { tenantCode, parentTenantCode } = tenant;
      // 2. 第二步：调用租户登录验证接口
      // 2.1 TODO 密码需要加密一下再传递;
      const loginParams = {
        userName: params.username,
        password: hashMd5(params.password), // 密码需要加密一下再传递;params.password,
        tenantCode,
        parentTenantCode,
      };
      // 返回信息应该保持原有的InResult接口定义
      // interface InResult<T> {
      //   code: number;
      //   errMsg: string;
      //   data: T;
      // }
      return new Promise<InResult<any>>((resolve, reject) => {
        verifyLogin(loginParams)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    // 修改 acquireUserInfo 方法
    // async acquireUserInfo(response: any) {
    //   const { data } = response;
    //   const userParams = {
    //     userId: data.userId,
    //   };

    //   try {
    //     const res = await getUserInfoApi(userParams);
    //     const userInfo = res;
    //     this.setRoles(userInfo.roleList);

    //     if (userInfo.permissionList && userInfo.permissionList.length > 0) {
    //       const permissionTrans = this.transformPermission(userInfo.permissionList);
    //       storage.set(CURRENT_PERMISSIONS, permissionTrans, expire);
    //       this.setPermissions(permissionTrans);
    //     }

    //     return res;
    //   } catch (err) {
    //     throw err;
    //   }
    // },

    acquireUserInfo(response: any) {
      const { data } = response;
      const userParams = {
        userId: data.userId,
      };
      return new Promise((resolve, reject) => {
        getUserInfoApi(userParams)
          .then((res) => {
            const userInfo = res;
            storage.set(CURRENT_ROLES,userInfo.roleList,expire);
            this.setRoles(userInfo.roleList);
            if (userInfo.permissionList && userInfo.permissionList.length > 0) {
              const permissionTrans = this.transformPermission(userInfo.permissionList);
              storage.set(CURRENT_PERMISSIONS, permissionTrans, expire);
              this.setPermissions(permissionTrans);
            }
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    transformPermission(permissionList: any) {
      return permissionList && permissionList.length
        ? permissionList
            .filter((r) => r.resourceType === 'M' || r.resourceType === 'B')
            .map((r) => {
              if (r.resourceType === 'M')
                return {
                  label: r.resourceId,
                  value: r.component,
                };
              if (r.resourceType === 'B')
                return {
                  label: r.resourceId,
                  value: r.permission,
                };
            })
        : [];
    },

    // 获取用户信息
    async getInfo() {
      const data = await getUserInfoApi();
      const { result } = data;
     
      if (result.permissions && result.permissions.length) {
        const permissionsList = result.permissions;
        console.log('set permissionsList', permissionsList);
        this.setPermissions(permissionsList);
        this.setUserInfo(result);
      } else {
        throw new Error('getInfo: permissionsList must be a non-null array !');
      }
      this.setAvatar(result.avatar);
      return result;
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo({ username: '', email: '' });
      this.setNickName('');
      this.setAvatar('');
      this.setPermissions([]);
      this.setRoles([]);

      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  return useUserStore(store);
}
